package com.xuqing.autohelpertesting;

import android.app.Activity;
import android.content.res.Resources;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import site.xuqing.autohelper.bean.StepInfoBean;

/**
 * @author xuqing
 * @Description 测试基类，需要自定义测试类的时候需要继承该类
 * @createTime 2022年03月24日 13:20:45
 */
public abstract class BaseTesting implements Testing {
    private Activity mActivity;
    private Fragment mFragment;
    private View mView;
    
    @Override
    public void setActivity(Activity activity) {
        mActivity = activity;
    }
    
    @Override
    public void setFragment(Fragment fragment) {
        mFragment = fragment;
    }
    
    @Override
    public void setView(View view) {
        mView = view;
    }
    
    @Override
    public <T extends View> T findViewById(String idName) {
        Resources res;
        int viewId;
        T data;
        if (mActivity != null) {
            res = mActivity.getResources();
            viewId = res.getIdentifier(idName, "id", mActivity.getPackageName());
            data = mActivity.findViewById(viewId);
        } else if (mFragment != null && mFragment.getActivity() != null && mFragment.getView() != null) {
            res = mFragment.getResources();
            viewId = res.getIdentifier(idName, "id", mFragment.getActivity().getPackageName());
            data = mFragment.getView().findViewById(viewId);
        } else if (mView != null) {
            res = mView.getResources();
            viewId = res.getIdentifier(idName, "id", mView.getContext().getPackageName());
            data = mView.findViewById(viewId);
        } else {
            throw new RuntimeException("please call setContext method!");
        }
        return data;
    }
    
    @Override
    public StepInfoBean getStepInfoBean(String idName) {
        StepInfoBean stepInfoBean = new StepInfoBean();
        View view = findViewById(idName);
        stepInfoBean.setClassName(view.getAccessibilityClassName().toString());
        stepInfoBean.setId(view.getContext().getPackageName() + ":id/" + idName);
        if (view instanceof TextView) {
            stepInfoBean.setText(((TextView) view).getText().toString());
        }
        return stepInfoBean;
    }
}
